Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [2]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [3]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [4]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

print(human_files[3])

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
lfw\Laurence_Fishburne\Laurence_Fishburne_0001.jpg
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [5]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: I got 99% of human images and 11% of dog images with detected faces. I also visualized incorrectly detected human and dog images. Some of the dog images have also humans (with visible faces) so the percentage of incorrectly detected faces is actually lower (10% in our case). The photo of Muhammad Ali was taken in profile and it could be a reason why it was not correctly detected. The other pictures seem to have front-on portraits.

In [6]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

# Tests detection performance and displays 
# incorrectly detected pictures. This function will also be used later for
# testing dog detection algorithms so it has additional parameters
def test_detect_performance(detector, object_string, report_human_errors):
    
    """Tests detection performance and displays incorrectly detected pictures. 
    
    Note: This function will also be used later for testing dog detection 
    algorithms so it has additional parameters


    Parameters
    ----------
    detector : function
        An object detection function. Example: face_detector

    object_string : str
        Object name in the detection report 

    report_human_errors : bool
        True, if the function is supposed to detect humans on the images, False if dogs
    """
    
    def object_detector(img_path):
        if report_human_errors:
            return not detector(img_path)
        else:
            return detector(img_path)
        
    def get_rate(img_list):
        if report_human_errors:
            return 100 - len(img_list)
        else:
            return len(img_list)
        
    # Get the list of incorrectly detected objects on human images
    no_human_list = list(filter(lambda x : object_detector(x), human_files_short))
    human_rate = get_rate(no_human_list)
    print("Percentage of human images with detected {}: {}%".format(object_string, human_rate))

    # Get the list of incorrectly detected objects on dog images    
    no_dog_list = list(filter(lambda x : not object_detector(x), dog_files_short))
    dog_rate = 100 - get_rate(no_dog_list)
    print("Percentage of dog images with detected {}: {}%".format(object_string, dog_rate))

    fig_human = plt.figure(figsize=(20, 2))

    for ind, img_path in enumerate(no_human_list):
        a = fig_human.add_subplot(1, len(no_human_list), ind + 1)
        img = cv2.imread(img_path)
        # convert BGR image to RGB for plotting
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)
        #a.set_title(img_path)

    fig_human.suptitle("Inorrectly detected human images")

    fig_dog = plt.figure(figsize=(20, 2))

    for ind, img_path in enumerate(no_dog_list):
        a = fig_dog.add_subplot(1, len(no_dog_list), ind + 1)
        img = cv2.imread(img_path)
        # convert BGR image to RGB for plotting
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)

    fig_dog.suptitle("Inorrectly detected dog images")

    plt.show()

test_detect_performance(face_detector, "faces", True)
Percentage of human images with detected faces: 99%
Percentage of dog images with detected faces: 11%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: For the purpouse of this project a clearly presented face is a reasonable expectation. If the user wants to find out what dog breed he/she looks like, they must provide a picture with a face. For the general human detection task we can use a different algorithm, for instance, the OpenCV HOG&SVM detector (see below).

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [7]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

# This is OpenCV full body detection method using HOG and SVM. As it is clear from the obtained results,
# it does not work well for picturs with human faces.  

import cv2  

hog = cv2.HOGDescriptor()
hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )

def human_detector(img_path):
    img = cv2.imread(img_path)
    rects, weights = hog.detectMultiScale(img, winStride=(2, 2),
        padding=(8, 8), scale=1.01)
    return len(rects) > 0

human_files_short = human_files[:100]

human_rate = len(list(filter(lambda x : human_detector(x), human_files_short)))
print("Percentage of human images with detected faces: {}%".format(human_rate))
Percentage of human images with detected faces: 42%

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [7]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [8]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [9]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [10]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: Only one image was detected incorrectly by the dog detection function. So I got 1% for human images and 100% for dog images. No idea why John Rigas was detected incorrectly, he does not look like a dog on the picture for me.

In [11]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

# use the test performance function defined above
test_detect_performance(dog_detector, "dogs", False)
Percentage of human images with detected dogs: 1%
Percentage of dog images with detected dogs: 100%
<matplotlib.figure.Figure at 0x145f3356160>

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [12]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|█████████████████████████████████████████████████████████████████████████████| 6680/6680 [00:37<00:00, 177.85it/s]
100%|███████████████████████████████████████████████████████████████████████████████| 835/835 [00:06<00:00, 121.37it/s]
100%|███████████████████████████████████████████████████████████████████████████████| 836/836 [00:06<00:00, 126.90it/s]
In [13]:
print(train_tensors.shape)
(6680, 224, 224, 3)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: I started with a CNN architecture that proved successful for the CIFAR10 project (I got almost 90% test rate with augmented data). That CNN had 6 convolutional layers, 2x128, 2x256 and 2x512 with kernel size 3, 2 fully connected layers with 2000 elements each and the output layer with 133 elements. Every dense layer, except for the output one, had 0.7 dropout rate. The optimizer was "adadelta". Unfortunately, that CNN did not fit to the memory of my graphics card (GeForce 970, 4G) thanks to the increased dimensions of the input images. So I had to decrease the numbers of filters to 64, 128, 256 respectively. After that I started experimenting with different numbers of dense layers and their dimensions, dropout rates, kernel initializers, batch normalization, GAP and flatten layers etc. Batch normalization had the biggest impact on the speed of learning. But I did not notice much difference when using various kernel initializers. My final architecture is the result of many days of experimenting. I got over 73% after 100 epochs, which is not that different from the results obtained with the state-of-the-art CNN architectures used in this project for transfer learning. I'm sure I can do better than that but I need more powerful hardware.

In [14]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, BatchNormalization, Activation
from keras.models import Sequential

model = Sequential()

model.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='relu', 
                        input_shape=(224, 224, 3)))

model.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=4))

model.add(BatchNormalization())
model.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='relu'))

model.add(BatchNormalization())
model.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))

model.add(BatchNormalization())
model.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='relu'))

model.add(BatchNormalization())
model.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))

model.add(BatchNormalization())
model.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='relu'))

model.add(BatchNormalization())
model.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=4))

model.add(BatchNormalization())
model.add(Flatten())

model.add(Dense(2000))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.6))

model.add(Dense(2000))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.6))

model.add(Dense(133))
model.add(BatchNormalization())
model.add(Activation('softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 64)      1792      
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 224, 224, 64)      36928     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 56, 56, 64)        0         
_________________________________________________________________
batch_normalization_1 (Batch (None, 56, 56, 64)        256       
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 128)       73856     
_________________________________________________________________
batch_normalization_2 (Batch (None, 56, 56, 128)       512       
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 56, 56, 128)       147584    
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 28, 28, 128)       0         
_________________________________________________________________
batch_normalization_3 (Batch (None, 28, 28, 128)       512       
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 28, 28, 256)       295168    
_________________________________________________________________
batch_normalization_4 (Batch (None, 28, 28, 256)       1024      
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 28, 28, 256)       590080    
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 14, 14, 256)       0         
_________________________________________________________________
batch_normalization_5 (Batch (None, 14, 14, 256)       1024      
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 14, 14, 512)       1180160   
_________________________________________________________________
batch_normalization_6 (Batch (None, 14, 14, 512)       2048      
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 14, 14, 512)       2359808   
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 3, 3, 512)         0         
_________________________________________________________________
batch_normalization_7 (Batch (None, 3, 3, 512)         2048      
_________________________________________________________________
flatten_2 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 2000)              9218000   
_________________________________________________________________
batch_normalization_8 (Batch (None, 2000)              8000      
_________________________________________________________________
activation_50 (Activation)   (None, 2000)              0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 2000)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 2000)              4002000   
_________________________________________________________________
batch_normalization_9 (Batch (None, 2000)              8000      
_________________________________________________________________
activation_51 (Activation)   (None, 2000)              0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 2000)              0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               266133    
_________________________________________________________________
batch_normalization_10 (Batc (None, 133)               532       
_________________________________________________________________
activation_52 (Activation)   (None, 133)               0         
=================================================================
Total params: 18,195,465
Trainable params: 18,183,487
Non-trainable params: 11,978
_________________________________________________________________

Compile the Model

In [15]:
model.compile(optimizer='adadelta', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [16]:
from keras.preprocessing.image import ImageDataGenerator

# create and configure augmented image generator
datagen_train = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True) # randomly flip images horizontally

# create and configure augmented image generator
datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True) # randomly flip images horizontally

# fit augmented image generator on data
datagen_train.fit(train_tensors)
datagen_valid.fit(valid_tensors)
In [17]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 100
batch_size = 20

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
                               verbose=1, save_best_only=True)
  

#model.fit(train_tensors, train_targets, 
#          validation_data=(valid_tensors, valid_targets),
#          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=2)

model.fit_generator(datagen_train.flow(train_tensors, train_targets, batch_size=batch_size),
                    steps_per_epoch=train_tensors.shape[0] // batch_size,
                    epochs=epochs, verbose=2, callbacks=[checkpointer],
                    validation_data=datagen_valid.flow(valid_tensors, valid_targets, batch_size=batch_size),
                    validation_steps=valid_tensors.shape[0] // batch_size)
Epoch 1/100
Epoch 00000: val_loss improved from inf to 4.95607, saving model to saved_models/weights.best.from_scratch.hdf5
109s - loss: 4.9150 - acc: 0.0193 - val_loss: 4.9561 - val_acc: 0.0122
Epoch 2/100
Epoch 00001: val_loss improved from 4.95607 to 4.27579, saving model to saved_models/weights.best.from_scratch.hdf5
110s - loss: 4.4813 - acc: 0.0431 - val_loss: 4.2758 - val_acc: 0.0564
Epoch 3/100
Epoch 00002: val_loss improved from 4.27579 to 4.27242, saving model to saved_models/weights.best.from_scratch.hdf5
106s - loss: 4.2951 - acc: 0.0581 - val_loss: 4.2724 - val_acc: 0.0601
Epoch 4/100
Epoch 00003: val_loss improved from 4.27242 to 4.08475, saving model to saved_models/weights.best.from_scratch.hdf5
106s - loss: 4.1552 - acc: 0.0817 - val_loss: 4.0848 - val_acc: 0.0957
Epoch 5/100
Epoch 00004: val_loss improved from 4.08475 to 4.07378, saving model to saved_models/weights.best.from_scratch.hdf5
106s - loss: 4.0185 - acc: 0.0934 - val_loss: 4.0738 - val_acc: 0.0982
Epoch 6/100
Epoch 00005: val_loss improved from 4.07378 to 3.84184, saving model to saved_models/weights.best.from_scratch.hdf5
106s - loss: 3.9013 - acc: 0.1129 - val_loss: 3.8418 - val_acc: 0.1362
Epoch 7/100
Epoch 00006: val_loss improved from 3.84184 to 3.57051, saving model to saved_models/weights.best.from_scratch.hdf5
108s - loss: 3.7818 - acc: 0.1368 - val_loss: 3.5705 - val_acc: 0.1804
Epoch 8/100
Epoch 00007: val_loss improved from 3.57051 to 3.54991, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 3.6787 - acc: 0.1612 - val_loss: 3.5499 - val_acc: 0.1791
Epoch 9/100
Epoch 00008: val_loss improved from 3.54991 to 3.44399, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 3.5677 - acc: 0.1928 - val_loss: 3.4440 - val_acc: 0.1914
Epoch 10/100
Epoch 00009: val_loss improved from 3.44399 to 3.26591, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 3.4923 - acc: 0.2066 - val_loss: 3.2659 - val_acc: 0.2429
Epoch 11/100
Epoch 00010: val_loss improved from 3.26591 to 3.10572, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 3.4050 - acc: 0.2299 - val_loss: 3.1057 - val_acc: 0.3141
Epoch 12/100
Epoch 00011: val_loss did not improve
103s - loss: 3.3368 - acc: 0.2437 - val_loss: 3.2145 - val_acc: 0.2773
Epoch 13/100
Epoch 00012: val_loss improved from 3.10572 to 3.01395, saving model to saved_models/weights.best.from_scratch.hdf5
105s - loss: 3.2580 - acc: 0.2668 - val_loss: 3.0140 - val_acc: 0.2945
Epoch 14/100
Epoch 00013: val_loss did not improve
103s - loss: 3.1701 - acc: 0.2915 - val_loss: 3.0205 - val_acc: 0.3018
Epoch 15/100
Epoch 00014: val_loss improved from 3.01395 to 2.88624, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 3.1310 - acc: 0.2991 - val_loss: 2.8862 - val_acc: 0.3215
Epoch 16/100
Epoch 00015: val_loss improved from 2.88624 to 2.81175, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 3.0637 - acc: 0.3160 - val_loss: 2.8117 - val_acc: 0.3840
Epoch 17/100
Epoch 00016: val_loss improved from 2.81175 to 2.68461, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.9877 - acc: 0.3368 - val_loss: 2.6846 - val_acc: 0.3975
Epoch 18/100
Epoch 00017: val_loss did not improve
103s - loss: 2.9292 - acc: 0.3588 - val_loss: 2.6984 - val_acc: 0.3902
Epoch 19/100
Epoch 00018: val_loss improved from 2.68461 to 2.62042, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.8924 - acc: 0.3654 - val_loss: 2.6204 - val_acc: 0.4098
Epoch 20/100
Epoch 00019: val_loss improved from 2.62042 to 2.59266, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.8191 - acc: 0.3910 - val_loss: 2.5927 - val_acc: 0.4368
Epoch 21/100
Epoch 00020: val_loss improved from 2.59266 to 2.32633, saving model to saved_models/weights.best.from_scratch.hdf5
105s - loss: 2.7706 - acc: 0.4076 - val_loss: 2.3263 - val_acc: 0.4663
Epoch 22/100
Epoch 00021: val_loss improved from 2.32633 to 2.32042, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.6941 - acc: 0.4296 - val_loss: 2.3204 - val_acc: 0.4429
Epoch 23/100
Epoch 00022: val_loss did not improve
103s - loss: 2.6621 - acc: 0.4337 - val_loss: 2.3528 - val_acc: 0.4613
Epoch 24/100
Epoch 00023: val_loss did not improve
104s - loss: 2.5783 - acc: 0.4593 - val_loss: 2.3236 - val_acc: 0.4626
Epoch 25/100
Epoch 00024: val_loss improved from 2.32042 to 2.29569, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.5402 - acc: 0.4723 - val_loss: 2.2957 - val_acc: 0.4564
Epoch 26/100
Epoch 00025: val_loss improved from 2.29569 to 2.14789, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.4910 - acc: 0.4823 - val_loss: 2.1479 - val_acc: 0.4736
Epoch 27/100
Epoch 00026: val_loss did not improve
103s - loss: 2.4382 - acc: 0.5057 - val_loss: 2.1497 - val_acc: 0.5276
Epoch 28/100
Epoch 00027: val_loss did not improve
103s - loss: 2.3879 - acc: 0.5093 - val_loss: 2.1935 - val_acc: 0.4933
Epoch 29/100
Epoch 00028: val_loss improved from 2.14789 to 2.05838, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.3363 - acc: 0.5317 - val_loss: 2.0584 - val_acc: 0.5325
Epoch 30/100
Epoch 00029: val_loss improved from 2.05838 to 1.97864, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.2780 - acc: 0.5421 - val_loss: 1.9786 - val_acc: 0.5055
Epoch 31/100
Epoch 00030: val_loss did not improve
104s - loss: 2.2469 - acc: 0.5575 - val_loss: 2.0106 - val_acc: 0.5276
Epoch 32/100
Epoch 00031: val_loss improved from 1.97864 to 1.96956, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.1835 - acc: 0.5778 - val_loss: 1.9696 - val_acc: 0.5472
Epoch 33/100
Epoch 00032: val_loss improved from 1.96956 to 1.89762, saving model to saved_models/weights.best.from_scratch.hdf5
106s - loss: 2.1522 - acc: 0.5861 - val_loss: 1.8976 - val_acc: 0.5595
Epoch 34/100
Epoch 00033: val_loss improved from 1.89762 to 1.76316, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 2.0984 - acc: 0.6075 - val_loss: 1.7632 - val_acc: 0.5644
Epoch 35/100
Epoch 00034: val_loss improved from 1.76316 to 1.67743, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 2.0474 - acc: 0.6121 - val_loss: 1.6774 - val_acc: 0.6086
Epoch 36/100
Epoch 00035: val_loss did not improve
103s - loss: 2.0099 - acc: 0.6268 - val_loss: 1.8080 - val_acc: 0.5718
Epoch 37/100
Epoch 00036: val_loss improved from 1.67743 to 1.66838, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 1.9627 - acc: 0.6430 - val_loss: 1.6684 - val_acc: 0.6074
Epoch 38/100
Epoch 00037: val_loss did not improve
103s - loss: 1.9179 - acc: 0.6504 - val_loss: 1.7775 - val_acc: 0.5706
Epoch 39/100
Epoch 00038: val_loss improved from 1.66838 to 1.66279, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 1.8891 - acc: 0.6534 - val_loss: 1.6628 - val_acc: 0.6098
Epoch 40/100
Epoch 00039: val_loss improved from 1.66279 to 1.65349, saving model to saved_models/weights.best.from_scratch.hdf5
104s - loss: 1.8417 - acc: 0.6669 - val_loss: 1.6535 - val_acc: 0.6025
Epoch 41/100
Epoch 00040: val_loss did not improve
103s - loss: 1.7960 - acc: 0.6882 - val_loss: 1.6922 - val_acc: 0.5988
Epoch 42/100
Epoch 00041: val_loss did not improve
103s - loss: 1.7714 - acc: 0.6889 - val_loss: 1.7912 - val_acc: 0.5644
Epoch 43/100
Epoch 00042: val_loss did not improve
103s - loss: 1.7335 - acc: 0.7036 - val_loss: 1.7630 - val_acc: 0.5620
Epoch 44/100
Epoch 00043: val_loss improved from 1.65349 to 1.59780, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.7045 - acc: 0.7075 - val_loss: 1.5978 - val_acc: 0.5963
Epoch 45/100
Epoch 00044: val_loss did not improve
103s - loss: 1.6566 - acc: 0.7207 - val_loss: 1.6022 - val_acc: 0.6233
Epoch 46/100
Epoch 00045: val_loss did not improve
103s - loss: 1.6289 - acc: 0.7323 - val_loss: 1.6562 - val_acc: 0.5951
Epoch 47/100
Epoch 00046: val_loss improved from 1.59780 to 1.48601, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.5894 - acc: 0.7443 - val_loss: 1.4860 - val_acc: 0.6589
Epoch 48/100
Epoch 00047: val_loss did not improve
103s - loss: 1.5683 - acc: 0.7481 - val_loss: 1.6500 - val_acc: 0.5914
Epoch 49/100
Epoch 00048: val_loss did not improve
102s - loss: 1.5228 - acc: 0.7578 - val_loss: 1.5063 - val_acc: 0.6368
Epoch 50/100
Epoch 00049: val_loss did not improve
102s - loss: 1.4909 - acc: 0.7660 - val_loss: 1.5357 - val_acc: 0.6025
Epoch 51/100
Epoch 00050: val_loss did not improve
102s - loss: 1.4495 - acc: 0.7713 - val_loss: 1.4870 - val_acc: 0.6258
Epoch 52/100
Epoch 00051: val_loss improved from 1.48601 to 1.39025, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.4186 - acc: 0.7780 - val_loss: 1.3902 - val_acc: 0.6613
Epoch 53/100
Epoch 00052: val_loss improved from 1.39025 to 1.38990, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.3952 - acc: 0.7907 - val_loss: 1.3899 - val_acc: 0.6466
Epoch 54/100
Epoch 00053: val_loss did not improve
103s - loss: 1.3679 - acc: 0.7940 - val_loss: 1.4632 - val_acc: 0.6491
Epoch 55/100
Epoch 00054: val_loss did not improve
102s - loss: 1.3403 - acc: 0.7969 - val_loss: 1.4215 - val_acc: 0.6601
Epoch 56/100
Epoch 00055: val_loss did not improve
102s - loss: 1.2778 - acc: 0.8190 - val_loss: 1.4352 - val_acc: 0.6564
Epoch 57/100
Epoch 00056: val_loss did not improve
103s - loss: 1.2864 - acc: 0.8069 - val_loss: 1.4009 - val_acc: 0.6601
Epoch 58/100
Epoch 00057: val_loss did not improve
103s - loss: 1.2471 - acc: 0.8284 - val_loss: 1.4319 - val_acc: 0.6417
Epoch 59/100
Epoch 00058: val_loss did not improve
103s - loss: 1.2395 - acc: 0.8234 - val_loss: 1.5062 - val_acc: 0.6245
Epoch 60/100
Epoch 00059: val_loss improved from 1.38990 to 1.31324, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.1940 - acc: 0.8391 - val_loss: 1.3132 - val_acc: 0.6724
Epoch 61/100
Epoch 00060: val_loss did not improve
103s - loss: 1.1638 - acc: 0.8491 - val_loss: 1.3691 - val_acc: 0.6613
Epoch 62/100
Epoch 00061: val_loss improved from 1.31324 to 1.28494, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 1.1511 - acc: 0.8446 - val_loss: 1.2849 - val_acc: 0.6908
Epoch 63/100
Epoch 00062: val_loss did not improve
103s - loss: 1.1243 - acc: 0.8579 - val_loss: 1.3739 - val_acc: 0.6675
Epoch 64/100
Epoch 00063: val_loss did not improve
103s - loss: 1.1092 - acc: 0.8545 - val_loss: 1.4675 - val_acc: 0.6380
Epoch 65/100
Epoch 00064: val_loss did not improve
102s - loss: 1.0673 - acc: 0.8692 - val_loss: 1.3333 - val_acc: 0.6798
Epoch 66/100
Epoch 00065: val_loss did not improve
102s - loss: 1.0508 - acc: 0.8717 - val_loss: 1.3879 - val_acc: 0.6552
Epoch 67/100
Epoch 00066: val_loss did not improve
102s - loss: 1.0196 - acc: 0.8795 - val_loss: 1.3622 - val_acc: 0.6748
Epoch 68/100
Epoch 00067: val_loss did not improve
102s - loss: 1.0068 - acc: 0.8783 - val_loss: 1.4472 - val_acc: 0.6638
Epoch 69/100
Epoch 00068: val_loss did not improve
103s - loss: 0.9795 - acc: 0.8892 - val_loss: 1.4112 - val_acc: 0.6503
Epoch 70/100
Epoch 00069: val_loss did not improve
102s - loss: 0.9591 - acc: 0.8864 - val_loss: 1.3334 - val_acc: 0.6834
Epoch 71/100
Epoch 00070: val_loss did not improve
102s - loss: 0.9390 - acc: 0.8921 - val_loss: 1.5711 - val_acc: 0.6221
Epoch 72/100
Epoch 00071: val_loss did not improve
103s - loss: 0.9292 - acc: 0.8957 - val_loss: 1.3734 - val_acc: 0.6834
Epoch 73/100
Epoch 00072: val_loss did not improve
102s - loss: 0.9025 - acc: 0.9018 - val_loss: 1.4309 - val_acc: 0.6613
Epoch 74/100
Epoch 00073: val_loss did not improve
102s - loss: 0.8743 - acc: 0.9057 - val_loss: 1.3893 - val_acc: 0.6785
Epoch 75/100
Epoch 00074: val_loss improved from 1.28494 to 1.26872, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 0.8657 - acc: 0.9091 - val_loss: 1.2687 - val_acc: 0.6982
Epoch 76/100
Epoch 00075: val_loss did not improve
102s - loss: 0.8417 - acc: 0.9102 - val_loss: 1.3064 - val_acc: 0.6871
Epoch 77/100
Epoch 00076: val_loss did not improve
103s - loss: 0.8285 - acc: 0.9175 - val_loss: 1.2816 - val_acc: 0.6748
Epoch 78/100
Epoch 00077: val_loss improved from 1.26872 to 1.26839, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 0.7932 - acc: 0.9199 - val_loss: 1.2684 - val_acc: 0.6908
Epoch 79/100
Epoch 00078: val_loss did not improve
102s - loss: 0.7859 - acc: 0.9237 - val_loss: 1.3525 - val_acc: 0.6933
Epoch 80/100
Epoch 00079: val_loss did not improve
103s - loss: 0.7607 - acc: 0.9310 - val_loss: 1.4046 - val_acc: 0.6748
Epoch 81/100
Epoch 00080: val_loss did not improve
103s - loss: 0.7458 - acc: 0.9308 - val_loss: 1.3041 - val_acc: 0.6933
Epoch 82/100
Epoch 00081: val_loss improved from 1.26839 to 1.26107, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 0.7452 - acc: 0.9280 - val_loss: 1.2611 - val_acc: 0.7141
Epoch 83/100
Epoch 00082: val_loss did not improve
102s - loss: 0.7198 - acc: 0.9317 - val_loss: 1.4222 - val_acc: 0.6736
Epoch 84/100
Epoch 00083: val_loss did not improve
102s - loss: 0.7047 - acc: 0.9361 - val_loss: 1.3397 - val_acc: 0.6994
Epoch 85/100
Epoch 00084: val_loss did not improve
102s - loss: 0.6845 - acc: 0.9415 - val_loss: 1.3458 - val_acc: 0.7006
Epoch 86/100
Epoch 00085: val_loss did not improve
103s - loss: 0.6722 - acc: 0.9407 - val_loss: 1.3447 - val_acc: 0.6847
Epoch 87/100
Epoch 00086: val_loss did not improve
103s - loss: 0.6514 - acc: 0.9448 - val_loss: 1.3249 - val_acc: 0.6933
Epoch 88/100
Epoch 00087: val_loss did not improve
102s - loss: 0.6411 - acc: 0.9451 - val_loss: 1.3083 - val_acc: 0.6896
Epoch 89/100
Epoch 00088: val_loss did not improve
102s - loss: 0.6325 - acc: 0.9455 - val_loss: 1.4742 - val_acc: 0.6896
Epoch 90/100
Epoch 00089: val_loss did not improve
103s - loss: 0.6052 - acc: 0.9503 - val_loss: 1.3881 - val_acc: 0.6859
Epoch 91/100
Epoch 00090: val_loss improved from 1.26107 to 1.21415, saving model to saved_models/weights.best.from_scratch.hdf5
103s - loss: 0.6130 - acc: 0.9467 - val_loss: 1.2142 - val_acc: 0.7190
Epoch 92/100
Epoch 00091: val_loss did not improve
103s - loss: 0.5910 - acc: 0.9491 - val_loss: 1.3587 - val_acc: 0.6920
Epoch 93/100
Epoch 00092: val_loss did not improve
103s - loss: 0.5768 - acc: 0.9551 - val_loss: 1.2391 - val_acc: 0.7129
Epoch 94/100
Epoch 00093: val_loss did not improve
103s - loss: 0.5650 - acc: 0.9566 - val_loss: 1.3827 - val_acc: 0.6969
Epoch 95/100
Epoch 00094: val_loss did not improve
103s - loss: 0.5455 - acc: 0.9587 - val_loss: 1.3194 - val_acc: 0.7018
Epoch 96/100
Epoch 00095: val_loss did not improve
103s - loss: 0.5415 - acc: 0.9600 - val_loss: 1.4086 - val_acc: 0.7129
Epoch 97/100
Epoch 00096: val_loss did not improve
103s - loss: 0.5243 - acc: 0.9582 - val_loss: 1.3321 - val_acc: 0.6969
Epoch 98/100
Epoch 00097: val_loss did not improve
102s - loss: 0.5172 - acc: 0.9645 - val_loss: 1.3604 - val_acc: 0.6957
Epoch 99/100
Epoch 00098: val_loss did not improve
103s - loss: 0.4970 - acc: 0.9650 - val_loss: 1.4063 - val_acc: 0.6748
Epoch 100/100
Epoch 00099: val_loss did not improve
102s - loss: 0.4960 - acc: 0.9630 - val_loss: 1.3156 - val_acc: 0.7043
Out[17]:
<keras.callbacks.History at 0x145f99ead30>

Load the Model with the Best Validation Loss

In [18]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [19]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 73.6842%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [20]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [21]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [22]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [23]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6520/6680 [============================>.] - ETA: 81s - loss: 14.5502 - acc: 0.0000e+0 - ETA: 7s - loss: 15.0422 - acc: 0.0115    - ETA: 3s - loss: 14.4425 - acc: 0.02 - ETA: 3s - loss: 14.3575 - acc: 0.02 - ETA: 2s - loss: 14.2237 - acc: 0.02 - ETA: 2s - loss: 14.0132 - acc: 0.03 - ETA: 1s - loss: 13.7959 - acc: 0.04 - ETA: 1s - loss: 13.6012 - acc: 0.04 - ETA: 1s - loss: 13.4110 - acc: 0.05 - ETA: 1s - loss: 13.2757 - acc: 0.06 - ETA: 1s - loss: 13.1357 - acc: 0.06 - ETA: 1s - loss: 13.0555 - acc: 0.07 - ETA: 1s - loss: 12.9566 - acc: 0.07 - ETA: 0s - loss: 12.8715 - acc: 0.08 - ETA: 0s - loss: 12.7524 - acc: 0.08 - ETA: 0s - loss: 12.6791 - acc: 0.09 - ETA: 0s - loss: 12.5987 - acc: 0.09 - ETA: 0s - loss: 12.4932 - acc: 0.10 - ETA: 0s - loss: 12.3997 - acc: 0.11 - ETA: 0s - loss: 12.3255 - acc: 0.11 - ETA: 0s - loss: 12.2543 - acc: 0.11 - ETA: 0s - loss: 12.2007 - acc: 0.12 - ETA: 0s - loss: 12.1509 - acc: 0.12 - ETA: 0s - loss: 12.0663 - acc: 0.13 - ETA: 0s - loss: 12.0050 - acc: 0.13 - ETA: 0s - loss: 11.9567 - acc: 0.1393Epoch 00000: val_loss improved from inf to 10.57099, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 11.9370 - acc: 0.1404 - val_loss: 10.5710 - val_acc: 0.2383
Epoch 2/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.4595 - acc: 0.400 - ETA: 1s - loss: 9.2561 - acc: 0.366 - ETA: 1s - loss: 10.0188 - acc: 0.30 - ETA: 1s - loss: 9.9914 - acc: 0.3041 - ETA: 1s - loss: 10.1535 - acc: 0.29 - ETA: 1s - loss: 10.2624 - acc: 0.29 - ETA: 1s - loss: 10.3079 - acc: 0.28 - ETA: 1s - loss: 10.2937 - acc: 0.29 - ETA: 0s - loss: 10.3640 - acc: 0.28 - ETA: 0s - loss: 10.3050 - acc: 0.29 - ETA: 0s - loss: 10.2738 - acc: 0.29 - ETA: 0s - loss: 10.2694 - acc: 0.29 - ETA: 0s - loss: 10.2523 - acc: 0.29 - ETA: 0s - loss: 10.1988 - acc: 0.29 - ETA: 0s - loss: 10.1324 - acc: 0.30 - ETA: 0s - loss: 10.1692 - acc: 0.29 - ETA: 0s - loss: 10.1252 - acc: 0.30 - ETA: 0s - loss: 10.1177 - acc: 0.30 - ETA: 0s - loss: 10.0706 - acc: 0.30 - ETA: 0s - loss: 10.1074 - acc: 0.30 - ETA: 0s - loss: 10.1330 - acc: 0.30 - ETA: 0s - loss: 10.1331 - acc: 0.30 - ETA: 0s - loss: 10.1534 - acc: 0.30 - ETA: 0s - loss: 10.1959 - acc: 0.29 - ETA: 0s - loss: 10.2025 - acc: 0.2980Epoch 00001: val_loss improved from 10.57099 to 10.09928, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.1921 - acc: 0.2987 - val_loss: 10.0993 - val_acc: 0.3054
Epoch 3/20
6640/6680 [============================>.] - ETA: 1s - loss: 9.9741 - acc: 0.350 - ETA: 1s - loss: 9.7754 - acc: 0.353 - ETA: 1s - loss: 10.1627 - acc: 0.32 - ETA: 1s - loss: 9.8900 - acc: 0.3394 - ETA: 1s - loss: 9.8715 - acc: 0.341 - ETA: 1s - loss: 9.9066 - acc: 0.337 - ETA: 1s - loss: 9.8685 - acc: 0.338 - ETA: 0s - loss: 9.7614 - acc: 0.345 - ETA: 0s - loss: 9.7237 - acc: 0.347 - ETA: 0s - loss: 9.7427 - acc: 0.348 - ETA: 0s - loss: 9.7629 - acc: 0.347 - ETA: 0s - loss: 9.7725 - acc: 0.345 - ETA: 0s - loss: 9.8063 - acc: 0.342 - ETA: 0s - loss: 9.7946 - acc: 0.344 - ETA: 0s - loss: 9.7569 - acc: 0.346 - ETA: 0s - loss: 9.7798 - acc: 0.345 - ETA: 0s - loss: 9.7955 - acc: 0.344 - ETA: 0s - loss: 9.7931 - acc: 0.344 - ETA: 0s - loss: 9.7624 - acc: 0.346 - ETA: 0s - loss: 9.7966 - acc: 0.344 - ETA: 0s - loss: 9.8107 - acc: 0.342 - ETA: 0s - loss: 9.7753 - acc: 0.344 - ETA: 0s - loss: 9.7727 - acc: 0.345 - ETA: 0s - loss: 9.7941 - acc: 0.343 - ETA: 0s - loss: 9.8265 - acc: 0.3420Epoch 00002: val_loss improved from 10.09928 to 10.07393, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.8183 - acc: 0.3425 - val_loss: 10.0739 - val_acc: 0.3150
Epoch 4/20
6400/6680 [===========================>..] - ETA: 1s - loss: 7.3164 - acc: 0.500 - ETA: 1s - loss: 8.9513 - acc: 0.420 - ETA: 1s - loss: 8.8063 - acc: 0.425 - ETA: 1s - loss: 9.3076 - acc: 0.397 - ETA: 1s - loss: 9.4489 - acc: 0.390 - ETA: 1s - loss: 9.5261 - acc: 0.381 - ETA: 1s - loss: 9.5657 - acc: 0.379 - ETA: 0s - loss: 9.4893 - acc: 0.381 - ETA: 0s - loss: 9.4800 - acc: 0.380 - ETA: 0s - loss: 9.4598 - acc: 0.381 - ETA: 0s - loss: 9.5631 - acc: 0.375 - ETA: 0s - loss: 9.6158 - acc: 0.371 - ETA: 0s - loss: 9.6308 - acc: 0.369 - ETA: 0s - loss: 9.6341 - acc: 0.370 - ETA: 0s - loss: 9.5922 - acc: 0.373 - ETA: 0s - loss: 9.6130 - acc: 0.372 - ETA: 0s - loss: 9.6693 - acc: 0.369 - ETA: 0s - loss: 9.6868 - acc: 0.367 - ETA: 0s - loss: 9.7256 - acc: 0.364 - ETA: 0s - loss: 9.7115 - acc: 0.365 - ETA: 0s - loss: 9.6817 - acc: 0.367 - ETA: 0s - loss: 9.6801 - acc: 0.367 - ETA: 0s - loss: 9.7191 - acc: 0.364 - ETA: 0s - loss: 9.6811 - acc: 0.3670Epoch 00003: val_loss improved from 10.07393 to 9.93498, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.6803 - acc: 0.3668 - val_loss: 9.9350 - val_acc: 0.3269
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 10.4534 - acc: 0.30 - ETA: 1s - loss: 10.0586 - acc: 0.35 - ETA: 1s - loss: 9.8109 - acc: 0.3741 - ETA: 1s - loss: 9.6539 - acc: 0.385 - ETA: 1s - loss: 9.6096 - acc: 0.382 - ETA: 1s - loss: 9.6533 - acc: 0.379 - ETA: 1s - loss: 9.7214 - acc: 0.374 - ETA: 1s - loss: 9.6958 - acc: 0.376 - ETA: 0s - loss: 9.6402 - acc: 0.378 - ETA: 0s - loss: 9.6429 - acc: 0.377 - ETA: 0s - loss: 9.5976 - acc: 0.382 - ETA: 0s - loss: 9.5952 - acc: 0.382 - ETA: 0s - loss: 9.5568 - acc: 0.384 - ETA: 0s - loss: 9.5728 - acc: 0.382 - ETA: 0s - loss: 9.5401 - acc: 0.383 - ETA: 0s - loss: 9.5364 - acc: 0.382 - ETA: 0s - loss: 9.5258 - acc: 0.383 - ETA: 0s - loss: 9.5638 - acc: 0.381 - ETA: 0s - loss: 9.5868 - acc: 0.379 - ETA: 0s - loss: 9.5810 - acc: 0.378 - ETA: 0s - loss: 9.5295 - acc: 0.382 - ETA: 0s - loss: 9.5093 - acc: 0.383 - ETA: 0s - loss: 9.5087 - acc: 0.383 - ETA: 0s - loss: 9.5440 - acc: 0.380 - ETA: 0s - loss: 9.5354 - acc: 0.3815Epoch 00004: val_loss improved from 9.93498 to 9.87837, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.5328 - acc: 0.3814 - val_loss: 9.8784 - val_acc: 0.3281
Epoch 6/20
6440/6680 [===========================>..] - ETA: 1s - loss: 8.1730 - acc: 0.450 - ETA: 1s - loss: 8.2134 - acc: 0.461 - ETA: 1s - loss: 9.0504 - acc: 0.421 - ETA: 1s - loss: 9.1309 - acc: 0.410 - ETA: 1s - loss: 9.2126 - acc: 0.404 - ETA: 1s - loss: 9.2638 - acc: 0.402 - ETA: 1s - loss: 9.3571 - acc: 0.398 - ETA: 0s - loss: 9.4277 - acc: 0.393 - ETA: 0s - loss: 9.4366 - acc: 0.394 - ETA: 0s - loss: 9.4155 - acc: 0.394 - ETA: 0s - loss: 9.4229 - acc: 0.394 - ETA: 0s - loss: 9.4186 - acc: 0.394 - ETA: 0s - loss: 9.3787 - acc: 0.396 - ETA: 0s - loss: 9.3418 - acc: 0.398 - ETA: 0s - loss: 9.3780 - acc: 0.396 - ETA: 0s - loss: 9.3981 - acc: 0.395 - ETA: 0s - loss: 9.4072 - acc: 0.395 - ETA: 0s - loss: 9.4389 - acc: 0.393 - ETA: 0s - loss: 9.4674 - acc: 0.391 - ETA: 0s - loss: 9.4463 - acc: 0.393 - ETA: 0s - loss: 9.4627 - acc: 0.392 - ETA: 0s - loss: 9.4143 - acc: 0.395 - ETA: 0s - loss: 9.4050 - acc: 0.396 - ETA: 0s - loss: 9.4211 - acc: 0.3955Epoch 00005: val_loss improved from 9.87837 to 9.75028, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.4129 - acc: 0.3961 - val_loss: 9.7503 - val_acc: 0.3473
Epoch 7/20
6460/6680 [============================>.] - ETA: 5s - loss: 8.8650 - acc: 0.450 - ETA: 1s - loss: 8.8995 - acc: 0.435 - ETA: 1s - loss: 8.8729 - acc: 0.429 - ETA: 1s - loss: 8.9114 - acc: 0.430 - ETA: 1s - loss: 8.9667 - acc: 0.426 - ETA: 1s - loss: 8.9745 - acc: 0.428 - ETA: 1s - loss: 9.0280 - acc: 0.426 - ETA: 0s - loss: 9.0106 - acc: 0.424 - ETA: 0s - loss: 9.0480 - acc: 0.421 - ETA: 0s - loss: 9.0532 - acc: 0.420 - ETA: 0s - loss: 9.0524 - acc: 0.420 - ETA: 0s - loss: 9.0488 - acc: 0.421 - ETA: 0s - loss: 9.0439 - acc: 0.421 - ETA: 0s - loss: 9.1780 - acc: 0.412 - ETA: 0s - loss: 9.1990 - acc: 0.411 - ETA: 0s - loss: 9.2117 - acc: 0.410 - ETA: 0s - loss: 9.1741 - acc: 0.412 - ETA: 0s - loss: 9.2165 - acc: 0.409 - ETA: 0s - loss: 9.2057 - acc: 0.410 - ETA: 0s - loss: 9.2299 - acc: 0.408 - ETA: 0s - loss: 9.2658 - acc: 0.406 - ETA: 0s - loss: 9.2632 - acc: 0.406 - ETA: 0s - loss: 9.2935 - acc: 0.4048Epoch 00006: val_loss improved from 9.75028 to 9.67861, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.3154 - acc: 0.4036 - val_loss: 9.6786 - val_acc: 0.3461
Epoch 8/20
6640/6680 [============================>.] - ETA: 1s - loss: 6.4619 - acc: 0.600 - ETA: 1s - loss: 9.2729 - acc: 0.415 - ETA: 1s - loss: 9.4631 - acc: 0.397 - ETA: 1s - loss: 9.0847 - acc: 0.419 - ETA: 1s - loss: 9.1819 - acc: 0.415 - ETA: 1s - loss: 9.1536 - acc: 0.416 - ETA: 0s - loss: 9.1937 - acc: 0.415 - ETA: 0s - loss: 9.0585 - acc: 0.425 - ETA: 0s - loss: 9.0632 - acc: 0.423 - ETA: 0s - loss: 9.0509 - acc: 0.424 - ETA: 0s - loss: 9.0990 - acc: 0.421 - ETA: 0s - loss: 9.2021 - acc: 0.415 - ETA: 0s - loss: 9.1995 - acc: 0.415 - ETA: 0s - loss: 9.2095 - acc: 0.415 - ETA: 0s - loss: 9.1797 - acc: 0.417 - ETA: 0s - loss: 9.1901 - acc: 0.416 - ETA: 0s - loss: 9.1793 - acc: 0.416 - ETA: 0s - loss: 9.1906 - acc: 0.416 - ETA: 0s - loss: 9.2156 - acc: 0.414 - ETA: 0s - loss: 9.2522 - acc: 0.412 - ETA: 0s - loss: 9.2369 - acc: 0.413 - ETA: 0s - loss: 9.2268 - acc: 0.413 - ETA: 0s - loss: 9.2493 - acc: 0.411 - ETA: 0s - loss: 9.2398 - acc: 0.4125Epoch 00007: val_loss improved from 9.67861 to 9.65863, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.2309 - acc: 0.4130 - val_loss: 9.6586 - val_acc: 0.3545
Epoch 9/20
6620/6680 [============================>.] - ETA: 1s - loss: 8.0672 - acc: 0.500 - ETA: 1s - loss: 8.7161 - acc: 0.452 - ETA: 1s - loss: 9.0328 - acc: 0.430 - ETA: 1s - loss: 8.9501 - acc: 0.437 - ETA: 1s - loss: 8.9310 - acc: 0.437 - ETA: 1s - loss: 9.1845 - acc: 0.421 - ETA: 0s - loss: 9.1141 - acc: 0.425 - ETA: 0s - loss: 9.0767 - acc: 0.426 - ETA: 0s - loss: 8.9759 - acc: 0.431 - ETA: 0s - loss: 9.0158 - acc: 0.429 - ETA: 0s - loss: 9.0365 - acc: 0.427 - ETA: 0s - loss: 9.0265 - acc: 0.427 - ETA: 0s - loss: 8.9958 - acc: 0.428 - ETA: 0s - loss: 9.0007 - acc: 0.428 - ETA: 0s - loss: 9.0028 - acc: 0.428 - ETA: 0s - loss: 8.9759 - acc: 0.429 - ETA: 0s - loss: 8.9991 - acc: 0.428 - ETA: 0s - loss: 8.9590 - acc: 0.431 - ETA: 0s - loss: 9.0046 - acc: 0.427 - ETA: 0s - loss: 9.0538 - acc: 0.423 - ETA: 0s - loss: 9.0362 - acc: 0.423 - ETA: 0s - loss: 9.0783 - acc: 0.420 - ETA: 0s - loss: 9.0786 - acc: 0.420 - ETA: 0s - loss: 9.0851 - acc: 0.4205Epoch 00008: val_loss improved from 9.65863 to 9.39818, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.0735 - acc: 0.4214 - val_loss: 9.3982 - val_acc: 0.3653
Epoch 10/20
6580/6680 [============================>.] - ETA: 1s - loss: 9.5598 - acc: 0.400 - ETA: 1s - loss: 8.9395 - acc: 0.431 - ETA: 1s - loss: 8.9214 - acc: 0.427 - ETA: 1s - loss: 8.7777 - acc: 0.438 - ETA: 1s - loss: 8.7866 - acc: 0.440 - ETA: 1s - loss: 8.7837 - acc: 0.442 - ETA: 1s - loss: 8.8418 - acc: 0.438 - ETA: 0s - loss: 8.8528 - acc: 0.438 - ETA: 0s - loss: 8.8901 - acc: 0.435 - ETA: 0s - loss: 8.9421 - acc: 0.432 - ETA: 0s - loss: 8.8973 - acc: 0.434 - ETA: 0s - loss: 8.8925 - acc: 0.434 - ETA: 0s - loss: 8.8935 - acc: 0.433 - ETA: 0s - loss: 8.8499 - acc: 0.433 - ETA: 0s - loss: 8.8252 - acc: 0.435 - ETA: 0s - loss: 8.7563 - acc: 0.439 - ETA: 0s - loss: 8.7606 - acc: 0.439 - ETA: 0s - loss: 8.7791 - acc: 0.438 - ETA: 0s - loss: 8.8289 - acc: 0.434 - ETA: 0s - loss: 8.8169 - acc: 0.435 - ETA: 0s - loss: 8.8192 - acc: 0.435 - ETA: 0s - loss: 8.8137 - acc: 0.435 - ETA: 0s - loss: 8.8218 - acc: 0.434 - ETA: 0s - loss: 8.8407 - acc: 0.432 - ETA: 0s - loss: 8.8680 - acc: 0.4305Epoch 00009: val_loss improved from 9.39818 to 9.21544, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.8809 - acc: 0.4296 - val_loss: 9.2154 - val_acc: 0.3737
Epoch 11/20
6460/6680 [============================>.] - ETA: 2s - loss: 8.8650 - acc: 0.450 - ETA: 1s - loss: 8.2634 - acc: 0.463 - ETA: 1s - loss: 8.5312 - acc: 0.450 - ETA: 1s - loss: 8.4994 - acc: 0.455 - ETA: 1s - loss: 8.5904 - acc: 0.450 - ETA: 1s - loss: 8.4116 - acc: 0.460 - ETA: 1s - loss: 8.4912 - acc: 0.452 - ETA: 0s - loss: 8.5945 - acc: 0.446 - ETA: 0s - loss: 8.6347 - acc: 0.445 - ETA: 0s - loss: 8.6010 - acc: 0.447 - ETA: 0s - loss: 8.5579 - acc: 0.449 - ETA: 0s - loss: 8.6072 - acc: 0.445 - ETA: 0s - loss: 8.6283 - acc: 0.444 - ETA: 0s - loss: 8.6626 - acc: 0.442 - ETA: 0s - loss: 8.6348 - acc: 0.443 - ETA: 0s - loss: 8.6404 - acc: 0.443 - ETA: 0s - loss: 8.6145 - acc: 0.445 - ETA: 0s - loss: 8.6358 - acc: 0.444 - ETA: 0s - loss: 8.6323 - acc: 0.445 - ETA: 0s - loss: 8.6544 - acc: 0.443 - ETA: 0s - loss: 8.6257 - acc: 0.445 - ETA: 0s - loss: 8.6411 - acc: 0.445 - ETA: 0s - loss: 8.6135 - acc: 0.446 - ETA: 0s - loss: 8.6248 - acc: 0.446 - ETA: 0s - loss: 8.6388 - acc: 0.445 - ETA: 0s - loss: 8.6482 - acc: 0.4447Epoch 00010: val_loss improved from 9.21544 to 9.13638, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6996 - acc: 0.4419 - val_loss: 9.1364 - val_acc: 0.3820
Epoch 12/20
6640/6680 [============================>.] - ETA: 1s - loss: 8.0591 - acc: 0.500 - ETA: 1s - loss: 8.8807 - acc: 0.430 - ETA: 1s - loss: 8.9474 - acc: 0.433 - ETA: 1s - loss: 8.8775 - acc: 0.437 - ETA: 1s - loss: 8.7576 - acc: 0.447 - ETA: 1s - loss: 8.8307 - acc: 0.442 - ETA: 0s - loss: 8.7543 - acc: 0.447 - ETA: 0s - loss: 8.7908 - acc: 0.445 - ETA: 0s - loss: 8.7750 - acc: 0.447 - ETA: 0s - loss: 8.7768 - acc: 0.446 - ETA: 0s - loss: 8.7176 - acc: 0.450 - ETA: 0s - loss: 8.6398 - acc: 0.454 - ETA: 0s - loss: 8.6619 - acc: 0.452 - ETA: 0s - loss: 8.6074 - acc: 0.456 - ETA: 0s - loss: 8.6257 - acc: 0.455 - ETA: 0s - loss: 8.6288 - acc: 0.455 - ETA: 0s - loss: 8.6462 - acc: 0.453 - ETA: 0s - loss: 8.6586 - acc: 0.453 - ETA: 0s - loss: 8.6776 - acc: 0.452 - ETA: 0s - loss: 8.6574 - acc: 0.453 - ETA: 0s - loss: 8.6444 - acc: 0.453 - ETA: 0s - loss: 8.6836 - acc: 0.450 - ETA: 0s - loss: 8.6696 - acc: 0.451 - ETA: 0s - loss: 8.6627 - acc: 0.452 - ETA: 0s - loss: 8.6494 - acc: 0.453 - ETA: 0s - loss: 8.6266 - acc: 0.4547Epoch 00011: val_loss improved from 9.13638 to 9.09018, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6304 - acc: 0.4545 - val_loss: 9.0902 - val_acc: 0.3892
Epoch 13/20
6440/6680 [===========================>..] - ETA: 1s - loss: 10.4768 - acc: 0.35 - ETA: 1s - loss: 8.3836 - acc: 0.4769 - ETA: 1s - loss: 8.9592 - acc: 0.442 - ETA: 1s - loss: 8.8667 - acc: 0.448 - ETA: 1s - loss: 8.8715 - acc: 0.446 - ETA: 1s - loss: 8.7322 - acc: 0.455 - ETA: 1s - loss: 8.8194 - acc: 0.449 - ETA: 1s - loss: 8.6353 - acc: 0.459 - ETA: 0s - loss: 8.5726 - acc: 0.463 - ETA: 0s - loss: 8.5447 - acc: 0.465 - ETA: 0s - loss: 8.5842 - acc: 0.462 - ETA: 0s - loss: 8.5980 - acc: 0.461 - ETA: 0s - loss: 8.6977 - acc: 0.455 - ETA: 0s - loss: 8.6759 - acc: 0.456 - ETA: 0s - loss: 8.6541 - acc: 0.457 - ETA: 0s - loss: 8.6158 - acc: 0.460 - ETA: 0s - loss: 8.6826 - acc: 0.456 - ETA: 0s - loss: 8.7405 - acc: 0.452 - ETA: 0s - loss: 8.7140 - acc: 0.453 - ETA: 0s - loss: 8.7072 - acc: 0.453 - ETA: 0s - loss: 8.6674 - acc: 0.455 - ETA: 0s - loss: 8.6354 - acc: 0.458 - ETA: 0s - loss: 8.6300 - acc: 0.458 - ETA: 0s - loss: 8.6214 - acc: 0.458 - ETA: 0s - loss: 8.6160 - acc: 0.458 - ETA: 0s - loss: 8.6047 - acc: 0.4592Epoch 00012: val_loss improved from 9.09018 to 9.05501, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6100 - acc: 0.4590 - val_loss: 9.0550 - val_acc: 0.3952
Epoch 14/20
6540/6680 [============================>.] - ETA: 1s - loss: 8.0590 - acc: 0.500 - ETA: 1s - loss: 9.2118 - acc: 0.428 - ETA: 1s - loss: 8.7859 - acc: 0.453 - ETA: 1s - loss: 8.3992 - acc: 0.472 - ETA: 1s - loss: 8.5682 - acc: 0.463 - ETA: 1s - loss: 8.6456 - acc: 0.459 - ETA: 0s - loss: 8.7552 - acc: 0.451 - ETA: 0s - loss: 8.6469 - acc: 0.458 - ETA: 0s - loss: 8.5725 - acc: 0.463 - ETA: 0s - loss: 8.4552 - acc: 0.471 - ETA: 0s - loss: 8.4081 - acc: 0.474 - ETA: 0s - loss: 8.4588 - acc: 0.470 - ETA: 0s - loss: 8.5223 - acc: 0.466 - ETA: 0s - loss: 8.5306 - acc: 0.465 - ETA: 0s - loss: 8.4903 - acc: 0.467 - ETA: 0s - loss: 8.5019 - acc: 0.466 - ETA: 0s - loss: 8.4964 - acc: 0.467 - ETA: 0s - loss: 8.5237 - acc: 0.465 - ETA: 0s - loss: 8.5104 - acc: 0.466 - ETA: 0s - loss: 8.5575 - acc: 0.463 - ETA: 0s - loss: 8.5329 - acc: 0.464 - ETA: 0s - loss: 8.5323 - acc: 0.464 - ETA: 0s - loss: 8.5253 - acc: 0.464 - ETA: 0s - loss: 8.5526 - acc: 0.463 - ETA: 0s - loss: 8.5527 - acc: 0.461 - ETA: 0s - loss: 8.6059 - acc: 0.4586Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.5855 - acc: 0.4599 - val_loss: 9.0789 - val_acc: 0.3832
Epoch 15/20
6420/6680 [===========================>..] - ETA: 1s - loss: 5.6420 - acc: 0.650 - ETA: 1s - loss: 8.2677 - acc: 0.482 - ETA: 1s - loss: 8.2667 - acc: 0.482 - ETA: 1s - loss: 8.1443 - acc: 0.487 - ETA: 1s - loss: 8.2802 - acc: 0.480 - ETA: 1s - loss: 8.4891 - acc: 0.464 - ETA: 0s - loss: 8.5486 - acc: 0.460 - ETA: 0s - loss: 8.5241 - acc: 0.462 - ETA: 0s - loss: 8.4162 - acc: 0.468 - ETA: 0s - loss: 8.4300 - acc: 0.468 - ETA: 0s - loss: 8.5024 - acc: 0.464 - ETA: 0s - loss: 8.5724 - acc: 0.460 - ETA: 0s - loss: 8.5600 - acc: 0.461 - ETA: 0s - loss: 8.4748 - acc: 0.466 - ETA: 0s - loss: 8.4480 - acc: 0.468 - ETA: 0s - loss: 8.4161 - acc: 0.470 - ETA: 0s - loss: 8.4736 - acc: 0.466 - ETA: 0s - loss: 8.4672 - acc: 0.467 - ETA: 0s - loss: 8.4607 - acc: 0.467 - ETA: 0s - loss: 8.4635 - acc: 0.467 - ETA: 0s - loss: 8.4488 - acc: 0.468 - ETA: 0s - loss: 8.4367 - acc: 0.469 - ETA: 0s - loss: 8.4514 - acc: 0.468 - ETA: 0s - loss: 8.4672 - acc: 0.467 - ETA: 0s - loss: 8.5077 - acc: 0.4651Epoch 00014: val_loss improved from 9.05501 to 9.04215, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.5052 - acc: 0.4651 - val_loss: 9.0421 - val_acc: 0.3856
Epoch 16/20
6600/6680 [============================>.] - ETA: 1s - loss: 9.6709 - acc: 0.400 - ETA: 1s - loss: 9.0585 - acc: 0.432 - ETA: 1s - loss: 8.9065 - acc: 0.444 - ETA: 1s - loss: 8.8785 - acc: 0.446 - ETA: 1s - loss: 8.8195 - acc: 0.449 - ETA: 1s - loss: 8.7476 - acc: 0.453 - ETA: 0s - loss: 8.8490 - acc: 0.446 - ETA: 0s - loss: 8.7514 - acc: 0.451 - ETA: 0s - loss: 8.6310 - acc: 0.459 - ETA: 0s - loss: 8.6007 - acc: 0.460 - ETA: 0s - loss: 8.6160 - acc: 0.458 - ETA: 0s - loss: 8.5847 - acc: 0.460 - ETA: 0s - loss: 8.5667 - acc: 0.461 - ETA: 0s - loss: 8.5710 - acc: 0.461 - ETA: 0s - loss: 8.5610 - acc: 0.461 - ETA: 0s - loss: 8.5641 - acc: 0.461 - ETA: 0s - loss: 8.5699 - acc: 0.460 - ETA: 0s - loss: 8.6017 - acc: 0.458 - ETA: 0s - loss: 8.5789 - acc: 0.459 - ETA: 0s - loss: 8.5470 - acc: 0.461 - ETA: 0s - loss: 8.5163 - acc: 0.463 - ETA: 0s - loss: 8.4858 - acc: 0.464 - ETA: 0s - loss: 8.4835 - acc: 0.464 - ETA: 0s - loss: 8.4824 - acc: 0.465 - ETA: 0s - loss: 8.4721 - acc: 0.465 - ETA: 0s - loss: 8.4535 - acc: 0.4658Epoch 00015: val_loss improved from 9.04215 to 9.01250, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.4516 - acc: 0.4659 - val_loss: 9.0125 - val_acc: 0.3880
Epoch 17/20
6540/6680 [============================>.] - ETA: 1s - loss: 9.6720 - acc: 0.400 - ETA: 1s - loss: 8.3039 - acc: 0.478 - ETA: 1s - loss: 8.5585 - acc: 0.464 - ETA: 1s - loss: 8.6811 - acc: 0.456 - ETA: 1s - loss: 8.7443 - acc: 0.450 - ETA: 1s - loss: 8.6454 - acc: 0.455 - ETA: 1s - loss: 8.4882 - acc: 0.466 - ETA: 0s - loss: 8.5043 - acc: 0.464 - ETA: 0s - loss: 8.4518 - acc: 0.467 - ETA: 0s - loss: 8.4722 - acc: 0.464 - ETA: 0s - loss: 8.5070 - acc: 0.462 - ETA: 0s - loss: 8.4654 - acc: 0.465 - ETA: 0s - loss: 8.4556 - acc: 0.466 - ETA: 0s - loss: 8.4636 - acc: 0.465 - ETA: 0s - loss: 8.4236 - acc: 0.467 - ETA: 0s - loss: 8.4101 - acc: 0.468 - ETA: 0s - loss: 8.3715 - acc: 0.469 - ETA: 0s - loss: 8.3508 - acc: 0.470 - ETA: 0s - loss: 8.3706 - acc: 0.468 - ETA: 0s - loss: 8.3490 - acc: 0.469 - ETA: 0s - loss: 8.3226 - acc: 0.470 - ETA: 0s - loss: 8.3171 - acc: 0.471 - ETA: 0s - loss: 8.3559 - acc: 0.468 - ETA: 0s - loss: 8.3302 - acc: 0.470 - ETA: 0s - loss: 8.2838 - acc: 0.473 - ETA: 0s - loss: 8.2891 - acc: 0.4729Epoch 00016: val_loss improved from 9.01250 to 8.87785, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.2948 - acc: 0.4726 - val_loss: 8.8779 - val_acc: 0.3904
Epoch 18/20
6600/6680 [============================>.] - ETA: 1s - loss: 9.7477 - acc: 0.350 - ETA: 1s - loss: 8.3968 - acc: 0.460 - ETA: 1s - loss: 8.5142 - acc: 0.460 - ETA: 1s - loss: 8.3665 - acc: 0.471 - ETA: 1s - loss: 8.4165 - acc: 0.470 - ETA: 1s - loss: 8.3368 - acc: 0.475 - ETA: 1s - loss: 8.3555 - acc: 0.472 - ETA: 1s - loss: 8.2249 - acc: 0.481 - ETA: 0s - loss: 8.2412 - acc: 0.480 - ETA: 0s - loss: 8.2961 - acc: 0.477 - ETA: 0s - loss: 8.1587 - acc: 0.485 - ETA: 0s - loss: 8.1352 - acc: 0.486 - ETA: 0s - loss: 8.1138 - acc: 0.487 - ETA: 0s - loss: 8.0942 - acc: 0.489 - ETA: 0s - loss: 8.1461 - acc: 0.485 - ETA: 0s - loss: 8.1440 - acc: 0.485 - ETA: 0s - loss: 8.1610 - acc: 0.484 - ETA: 0s - loss: 8.1802 - acc: 0.482 - ETA: 0s - loss: 8.1367 - acc: 0.485 - ETA: 0s - loss: 8.1285 - acc: 0.485 - ETA: 0s - loss: 8.1075 - acc: 0.486 - ETA: 0s - loss: 8.1241 - acc: 0.485 - ETA: 0s - loss: 8.1325 - acc: 0.484 - ETA: 0s - loss: 8.1148 - acc: 0.485 - ETA: 0s - loss: 8.1128 - acc: 0.486 - ETA: 0s - loss: 8.1060 - acc: 0.4865Epoch 00017: val_loss improved from 8.87785 to 8.66295, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.0997 - acc: 0.4870 - val_loss: 8.6629 - val_acc: 0.4180
Epoch 19/20
6420/6680 [===========================>..] - ETA: 0s - loss: 7.2531 - acc: 0.550 - ETA: 1s - loss: 8.1779 - acc: 0.483 - ETA: 1s - loss: 7.6546 - acc: 0.512 - ETA: 1s - loss: 7.9220 - acc: 0.498 - ETA: 1s - loss: 8.1167 - acc: 0.487 - ETA: 1s - loss: 8.0804 - acc: 0.490 - ETA: 1s - loss: 8.0114 - acc: 0.495 - ETA: 1s - loss: 8.1228 - acc: 0.488 - ETA: 1s - loss: 8.1158 - acc: 0.486 - ETA: 1s - loss: 8.1038 - acc: 0.486 - ETA: 0s - loss: 8.1197 - acc: 0.485 - ETA: 0s - loss: 8.1047 - acc: 0.486 - ETA: 0s - loss: 8.1121 - acc: 0.485 - ETA: 0s - loss: 8.1358 - acc: 0.483 - ETA: 0s - loss: 8.1187 - acc: 0.483 - ETA: 0s - loss: 8.1623 - acc: 0.481 - ETA: 0s - loss: 8.1610 - acc: 0.481 - ETA: 0s - loss: 8.1303 - acc: 0.483 - ETA: 0s - loss: 8.0736 - acc: 0.487 - ETA: 0s - loss: 8.1040 - acc: 0.484 - ETA: 0s - loss: 8.0969 - acc: 0.485 - ETA: 0s - loss: 8.1293 - acc: 0.483 - ETA: 0s - loss: 8.1101 - acc: 0.484 - ETA: 0s - loss: 8.1048 - acc: 0.484 - ETA: 0s - loss: 8.0797 - acc: 0.486 - ETA: 0s - loss: 8.0633 - acc: 0.487 - ETA: 0s - loss: 8.0388 - acc: 0.4891Epoch 00018: val_loss improved from 8.66295 to 8.64261, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.0347 - acc: 0.4891 - val_loss: 8.6426 - val_acc: 0.4180
Epoch 20/20
6660/6680 [============================>.] - ETA: 1s - loss: 5.6413 - acc: 0.650 - ETA: 1s - loss: 8.1950 - acc: 0.476 - ETA: 1s - loss: 7.7541 - acc: 0.506 - ETA: 1s - loss: 7.7604 - acc: 0.506 - ETA: 1s - loss: 7.7528 - acc: 0.505 - ETA: 1s - loss: 7.7357 - acc: 0.508 - ETA: 0s - loss: 7.5719 - acc: 0.520 - ETA: 0s - loss: 7.6399 - acc: 0.516 - ETA: 0s - loss: 7.6301 - acc: 0.517 - ETA: 0s - loss: 7.6768 - acc: 0.515 - ETA: 0s - loss: 7.7458 - acc: 0.510 - ETA: 0s - loss: 7.7789 - acc: 0.509 - ETA: 0s - loss: 7.7610 - acc: 0.510 - ETA: 0s - loss: 7.7876 - acc: 0.508 - ETA: 0s - loss: 7.7786 - acc: 0.509 - ETA: 0s - loss: 7.8419 - acc: 0.505 - ETA: 0s - loss: 7.8783 - acc: 0.503 - ETA: 0s - loss: 7.9270 - acc: 0.500 - ETA: 0s - loss: 7.9201 - acc: 0.500 - ETA: 0s - loss: 7.9394 - acc: 0.499 - ETA: 0s - loss: 8.0020 - acc: 0.495 - ETA: 0s - loss: 7.9515 - acc: 0.498 - ETA: 0s - loss: 7.9583 - acc: 0.497 - ETA: 0s - loss: 7.9803 - acc: 0.496 - ETA: 0s - loss: 7.9766 - acc: 0.4971Epoch 00019: val_loss improved from 8.64261 to 8.57165, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.9793 - acc: 0.4970 - val_loss: 8.5717 - val_acc: 0.4192
Out[23]:
<keras.callbacks.History at 0x145d46a5c50>

Load the Model with the Best Validation Loss

In [24]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [25]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 42.1053%

Predict Dog Breed with the Model

In [26]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

import matplotlib.pyplot as plt                        
%matplotlib inline                               

dog_file = train_files[2]
print(dog_file)

# load color (BGR) image
img = cv2.imread(dog_file)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(cv_rgb)

dog_breed = VGG16_predict_breed(dog_file)
print(dog_breed)
dogImages/train\088.Irish_water_spaniel\Irish_water_spaniel_06014.jpg
American_water_spaniel

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [27]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']

print(train_Xception.shape)
print(train_targets.shape)
(6680, 7, 7, 2048)
(6680, 133)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: The bottleneck data are the features generated by the convulutional layers of the pre-trained CNN models. We can use them as input to a simple network with dense layers only. I've got the best results with a simple netowork that has only 3 layers: a global average pooling layer, a fully connected layer with 2000 elements and a fully connect ouput layer with 133 elements for each dog category. I obtained the following test accuracy results for each pre-trained CNN:

InceptionV3: 82.66% Resnet50: 84.57% VGG19: 80.87% Xception: 86.48%

I also tried to re-train one of the models (Xception) using our dog database and I got slightly better result: 86.72 (the code and results are in cell 33 below).

In [28]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, BatchNormalization, Activation
from keras.models import Sequential

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))

Xception_model.add(Dense(2000))
Xception_model.add(BatchNormalization())
Xception_model.add(Activation('relu'))
Xception_model.add(Dropout(0.5))

Xception_model.add(Dense(133))
Xception_model.add(BatchNormalization())
Xception_model.add(Activation('softmax'))
Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 2000)              4098000   
_________________________________________________________________
batch_normalization_11 (Batc (None, 2000)              8000      
_________________________________________________________________
activation_53 (Activation)   (None, 2000)              0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 2000)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               266133    
_________________________________________________________________
batch_normalization_12 (Batc (None, 133)               532       
_________________________________________________________________
activation_54 (Activation)   (None, 133)               0         
=================================================================
Total params: 4,372,665
Trainable params: 4,368,399
Non-trainable params: 4,266
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [29]:
### TODO: Compile the model.
Xception_model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [30]:
### TODO: Train the model.
from keras.callbacks import ModelCheckpoint  

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
Epoch 00000: val_loss improved from inf to 0.83836, saving model to saved_models/weights.best.Xception.hdf5
6s - loss: 2.4648 - acc: 0.6225 - val_loss: 0.8384 - val_acc: 0.8419
Epoch 2/20
Epoch 00001: val_loss improved from 0.83836 to 0.68202, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.9646 - acc: 0.7629 - val_loss: 0.6820 - val_acc: 0.8347
Epoch 3/20
Epoch 00002: val_loss improved from 0.68202 to 0.65736, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.8328 - acc: 0.7904 - val_loss: 0.6574 - val_acc: 0.8395
Epoch 4/20
Epoch 00003: val_loss improved from 0.65736 to 0.63706, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.7453 - acc: 0.8129 - val_loss: 0.6371 - val_acc: 0.8455
Epoch 5/20
Epoch 00004: val_loss improved from 0.63706 to 0.62641, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.6885 - acc: 0.8196 - val_loss: 0.6264 - val_acc: 0.8539
Epoch 6/20
Epoch 00005: val_loss improved from 0.62641 to 0.61159, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.6124 - acc: 0.8287 - val_loss: 0.6116 - val_acc: 0.8575
Epoch 7/20
Epoch 00006: val_loss improved from 0.61159 to 0.60226, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.5400 - acc: 0.8439 - val_loss: 0.6023 - val_acc: 0.8611
Epoch 8/20
Epoch 00007: val_loss did not improve
5s - loss: 1.4875 - acc: 0.8578 - val_loss: 0.6072 - val_acc: 0.8599
Epoch 9/20
Epoch 00008: val_loss did not improve
5s - loss: 1.4380 - acc: 0.8692 - val_loss: 0.6038 - val_acc: 0.8539
Epoch 10/20
Epoch 00009: val_loss did not improve
5s - loss: 1.4038 - acc: 0.8696 - val_loss: 0.6029 - val_acc: 0.8599
Epoch 11/20
Epoch 00010: val_loss improved from 0.60226 to 0.59240, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.3606 - acc: 0.8747 - val_loss: 0.5924 - val_acc: 0.8575
Epoch 12/20
Epoch 00011: val_loss did not improve
5s - loss: 1.3049 - acc: 0.8882 - val_loss: 0.6120 - val_acc: 0.8599
Epoch 13/20
Epoch 00012: val_loss did not improve
5s - loss: 1.2688 - acc: 0.8865 - val_loss: 0.6091 - val_acc: 0.8563
Epoch 14/20
Epoch 00013: val_loss did not improve
5s - loss: 1.2378 - acc: 0.8967 - val_loss: 0.6165 - val_acc: 0.8587
Epoch 15/20
Epoch 00014: val_loss did not improve
5s - loss: 1.1913 - acc: 0.9039 - val_loss: 0.5981 - val_acc: 0.8647
Epoch 16/20
Epoch 00015: val_loss did not improve
5s - loss: 1.1361 - acc: 0.9112 - val_loss: 0.5985 - val_acc: 0.8659
Epoch 17/20
Epoch 00016: val_loss did not improve
5s - loss: 1.1096 - acc: 0.9183 - val_loss: 0.6065 - val_acc: 0.8647
Epoch 18/20
Epoch 00017: val_loss did not improve
5s - loss: 1.0729 - acc: 0.9216 - val_loss: 0.6030 - val_acc: 0.8647
Epoch 19/20
Epoch 00018: val_loss did not improve
5s - loss: 1.0633 - acc: 0.9192 - val_loss: 0.5994 - val_acc: 0.8587
Epoch 20/20
Epoch 00019: val_loss did not improve
5s - loss: 1.0098 - acc: 0.9259 - val_loss: 0.5969 - val_acc: 0.8683
Out[30]:
<keras.callbacks.History at 0x148d35ce9e8>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [31]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [32]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 85.6459%
In [33]:
# Train Xception CNN on augmented dog database

from keras.applications.xception import Xception
from keras.models import Model

initial_model = Xception(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = initial_model.output
x = GlobalAveragePooling2D()(x)

x = Dense(2000)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Dropout(0.5)(x)

x = Dense(133)(x)
x = BatchNormalization()(x)
x = Activation('softmax')(x)

# Freeze top layers of the network 
FREEZE_LAYER_NUM = 30
print(len(initial_model.layers))
for i, layer in enumerate(initial_model.layers):
    if i < FREEZE_LAYER_NUM:
        layer.trainable = False
    
augm_model = Model(inputs=initial_model.input, outputs=x)

augm_model.summary()

augm_model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])
    
epochs = 20
batch_size = 20

chkpt_file_path = 'saved_models/weights.best.XceptionAugm.hdf5'
checkpointer_augm = ModelCheckpoint(filepath=chkpt_file_path, 
                               verbose=1, monitor='val_acc', save_best_only=True)

augm_model.fit_generator(datagen_train.flow(train_tensors, train_targets, batch_size=batch_size),
                    steps_per_epoch=train_tensors.shape[0] // batch_size,
                    epochs=epochs, verbose=2, callbacks=[checkpointer_augm],
                    validation_data=datagen_valid.flow(valid_tensors, valid_targets, batch_size=batch_size),
                    validation_steps=valid_tensors.shape[0] // batch_size)

augm_model.load_weights(chkpt_file_path)

augm_predictions = [np.argmax(augm_model.predict(np.expand_dims(feature, axis=0))) for feature in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(augm_predictions)==np.argmax(test_targets, axis=1))/len(augm_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
132
____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_3 (InputLayer)             (None, None, None, 3) 0                                            
____________________________________________________________________________________________________
block1_conv1 (Conv2D)            (None, None, None, 32 864         input_3[0][0]                    
____________________________________________________________________________________________________
block1_conv1_bn (BatchNormalizat (None, None, None, 32 128         block1_conv1[0][0]               
____________________________________________________________________________________________________
block1_conv1_act (Activation)    (None, None, None, 32 0           block1_conv1_bn[0][0]            
____________________________________________________________________________________________________
block1_conv2 (Conv2D)            (None, None, None, 64 18432       block1_conv1_act[0][0]           
____________________________________________________________________________________________________
block1_conv2_bn (BatchNormalizat (None, None, None, 64 256         block1_conv2[0][0]               
____________________________________________________________________________________________________
block1_conv2_act (Activation)    (None, None, None, 64 0           block1_conv2_bn[0][0]            
____________________________________________________________________________________________________
block2_sepconv1 (SeparableConv2D (None, None, None, 12 8768        block1_conv2_act[0][0]           
____________________________________________________________________________________________________
block2_sepconv1_bn (BatchNormali (None, None, None, 12 512         block2_sepconv1[0][0]            
____________________________________________________________________________________________________
block2_sepconv2_act (Activation) (None, None, None, 12 0           block2_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block2_sepconv2 (SeparableConv2D (None, None, None, 12 17536       block2_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block2_sepconv2_bn (BatchNormali (None, None, None, 12 512         block2_sepconv2[0][0]            
____________________________________________________________________________________________________
conv2d_9 (Conv2D)                (None, None, None, 12 8192        block1_conv2_act[0][0]           
____________________________________________________________________________________________________
block2_pool (MaxPooling2D)       (None, None, None, 12 0           block2_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
batch_normalization_13 (BatchNor (None, None, None, 12 512         conv2d_9[0][0]                   
____________________________________________________________________________________________________
add_17 (Add)                     (None, None, None, 12 0           block2_pool[0][0]                
                                                                   batch_normalization_13[0][0]     
____________________________________________________________________________________________________
block3_sepconv1_act (Activation) (None, None, None, 12 0           add_17[0][0]                     
____________________________________________________________________________________________________
block3_sepconv1 (SeparableConv2D (None, None, None, 25 33920       block3_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block3_sepconv1_bn (BatchNormali (None, None, None, 25 1024        block3_sepconv1[0][0]            
____________________________________________________________________________________________________
block3_sepconv2_act (Activation) (None, None, None, 25 0           block3_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block3_sepconv2 (SeparableConv2D (None, None, None, 25 67840       block3_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block3_sepconv2_bn (BatchNormali (None, None, None, 25 1024        block3_sepconv2[0][0]            
____________________________________________________________________________________________________
conv2d_10 (Conv2D)               (None, None, None, 25 32768       add_17[0][0]                     
____________________________________________________________________________________________________
block3_pool (MaxPooling2D)       (None, None, None, 25 0           block3_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
batch_normalization_14 (BatchNor (None, None, None, 25 1024        conv2d_10[0][0]                  
____________________________________________________________________________________________________
add_18 (Add)                     (None, None, None, 25 0           block3_pool[0][0]                
                                                                   batch_normalization_14[0][0]     
____________________________________________________________________________________________________
block4_sepconv1_act (Activation) (None, None, None, 25 0           add_18[0][0]                     
____________________________________________________________________________________________________
block4_sepconv1 (SeparableConv2D (None, None, None, 72 188672      block4_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block4_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block4_sepconv1[0][0]            
____________________________________________________________________________________________________
block4_sepconv2_act (Activation) (None, None, None, 72 0           block4_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block4_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block4_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block4_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block4_sepconv2[0][0]            
____________________________________________________________________________________________________
conv2d_11 (Conv2D)               (None, None, None, 72 186368      add_18[0][0]                     
____________________________________________________________________________________________________
block4_pool (MaxPooling2D)       (None, None, None, 72 0           block4_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
batch_normalization_15 (BatchNor (None, None, None, 72 2912        conv2d_11[0][0]                  
____________________________________________________________________________________________________
add_19 (Add)                     (None, None, None, 72 0           block4_pool[0][0]                
                                                                   batch_normalization_15[0][0]     
____________________________________________________________________________________________________
block5_sepconv1_act (Activation) (None, None, None, 72 0           add_19[0][0]                     
____________________________________________________________________________________________________
block5_sepconv1 (SeparableConv2D (None, None, None, 72 536536      block5_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block5_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block5_sepconv1[0][0]            
____________________________________________________________________________________________________
block5_sepconv2_act (Activation) (None, None, None, 72 0           block5_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block5_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block5_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block5_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block5_sepconv2[0][0]            
____________________________________________________________________________________________________
block5_sepconv3_act (Activation) (None, None, None, 72 0           block5_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
block5_sepconv3 (SeparableConv2D (None, None, None, 72 536536      block5_sepconv3_act[0][0]        
____________________________________________________________________________________________________
block5_sepconv3_bn (BatchNormali (None, None, None, 72 2912        block5_sepconv3[0][0]            
____________________________________________________________________________________________________
add_20 (Add)                     (None, None, None, 72 0           block5_sepconv3_bn[0][0]         
                                                                   add_19[0][0]                     
____________________________________________________________________________________________________
block6_sepconv1_act (Activation) (None, None, None, 72 0           add_20[0][0]                     
____________________________________________________________________________________________________
block6_sepconv1 (SeparableConv2D (None, None, None, 72 536536      block6_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block6_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block6_sepconv1[0][0]            
____________________________________________________________________________________________________
block6_sepconv2_act (Activation) (None, None, None, 72 0           block6_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block6_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block6_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block6_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block6_sepconv2[0][0]            
____________________________________________________________________________________________________
block6_sepconv3_act (Activation) (None, None, None, 72 0           block6_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
block6_sepconv3 (SeparableConv2D (None, None, None, 72 536536      block6_sepconv3_act[0][0]        
____________________________________________________________________________________________________
block6_sepconv3_bn (BatchNormali (None, None, None, 72 2912        block6_sepconv3[0][0]            
____________________________________________________________________________________________________
add_21 (Add)                     (None, None, None, 72 0           block6_sepconv3_bn[0][0]         
                                                                   add_20[0][0]                     
____________________________________________________________________________________________________
block7_sepconv1_act (Activation) (None, None, None, 72 0           add_21[0][0]                     
____________________________________________________________________________________________________
block7_sepconv1 (SeparableConv2D (None, None, None, 72 536536      block7_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block7_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block7_sepconv1[0][0]            
____________________________________________________________________________________________________
block7_sepconv2_act (Activation) (None, None, None, 72 0           block7_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block7_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block7_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block7_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block7_sepconv2[0][0]            
____________________________________________________________________________________________________
block7_sepconv3_act (Activation) (None, None, None, 72 0           block7_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
block7_sepconv3 (SeparableConv2D (None, None, None, 72 536536      block7_sepconv3_act[0][0]        
____________________________________________________________________________________________________
block7_sepconv3_bn (BatchNormali (None, None, None, 72 2912        block7_sepconv3[0][0]            
____________________________________________________________________________________________________
add_22 (Add)                     (None, None, None, 72 0           block7_sepconv3_bn[0][0]         
                                                                   add_21[0][0]                     
____________________________________________________________________________________________________
block8_sepconv1_act (Activation) (None, None, None, 72 0           add_22[0][0]                     
____________________________________________________________________________________________________
block8_sepconv1 (SeparableConv2D (None, None, None, 72 536536      block8_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block8_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block8_sepconv1[0][0]            
____________________________________________________________________________________________________
block8_sepconv2_act (Activation) (None, None, None, 72 0           block8_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block8_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block8_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block8_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block8_sepconv2[0][0]            
____________________________________________________________________________________________________
block8_sepconv3_act (Activation) (None, None, None, 72 0           block8_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
block8_sepconv3 (SeparableConv2D (None, None, None, 72 536536      block8_sepconv3_act[0][0]        
____________________________________________________________________________________________________
block8_sepconv3_bn (BatchNormali (None, None, None, 72 2912        block8_sepconv3[0][0]            
____________________________________________________________________________________________________
add_23 (Add)                     (None, None, None, 72 0           block8_sepconv3_bn[0][0]         
                                                                   add_22[0][0]                     
____________________________________________________________________________________________________
block9_sepconv1_act (Activation) (None, None, None, 72 0           add_23[0][0]                     
____________________________________________________________________________________________________
block9_sepconv1 (SeparableConv2D (None, None, None, 72 536536      block9_sepconv1_act[0][0]        
____________________________________________________________________________________________________
block9_sepconv1_bn (BatchNormali (None, None, None, 72 2912        block9_sepconv1[0][0]            
____________________________________________________________________________________________________
block9_sepconv2_act (Activation) (None, None, None, 72 0           block9_sepconv1_bn[0][0]         
____________________________________________________________________________________________________
block9_sepconv2 (SeparableConv2D (None, None, None, 72 536536      block9_sepconv2_act[0][0]        
____________________________________________________________________________________________________
block9_sepconv2_bn (BatchNormali (None, None, None, 72 2912        block9_sepconv2[0][0]            
____________________________________________________________________________________________________
block9_sepconv3_act (Activation) (None, None, None, 72 0           block9_sepconv2_bn[0][0]         
____________________________________________________________________________________________________
block9_sepconv3 (SeparableConv2D (None, None, None, 72 536536      block9_sepconv3_act[0][0]        
____________________________________________________________________________________________________
block9_sepconv3_bn (BatchNormali (None, None, None, 72 2912        block9_sepconv3[0][0]            
____________________________________________________________________________________________________
add_24 (Add)                     (None, None, None, 72 0           block9_sepconv3_bn[0][0]         
                                                                   add_23[0][0]                     
____________________________________________________________________________________________________
block10_sepconv1_act (Activation (None, None, None, 72 0           add_24[0][0]                     
____________________________________________________________________________________________________
block10_sepconv1 (SeparableConv2 (None, None, None, 72 536536      block10_sepconv1_act[0][0]       
____________________________________________________________________________________________________
block10_sepconv1_bn (BatchNormal (None, None, None, 72 2912        block10_sepconv1[0][0]           
____________________________________________________________________________________________________
block10_sepconv2_act (Activation (None, None, None, 72 0           block10_sepconv1_bn[0][0]        
____________________________________________________________________________________________________
block10_sepconv2 (SeparableConv2 (None, None, None, 72 536536      block10_sepconv2_act[0][0]       
____________________________________________________________________________________________________
block10_sepconv2_bn (BatchNormal (None, None, None, 72 2912        block10_sepconv2[0][0]           
____________________________________________________________________________________________________
block10_sepconv3_act (Activation (None, None, None, 72 0           block10_sepconv2_bn[0][0]        
____________________________________________________________________________________________________
block10_sepconv3 (SeparableConv2 (None, None, None, 72 536536      block10_sepconv3_act[0][0]       
____________________________________________________________________________________________________
block10_sepconv3_bn (BatchNormal (None, None, None, 72 2912        block10_sepconv3[0][0]           
____________________________________________________________________________________________________
add_25 (Add)                     (None, None, None, 72 0           block10_sepconv3_bn[0][0]        
                                                                   add_24[0][0]                     
____________________________________________________________________________________________________
block11_sepconv1_act (Activation (None, None, None, 72 0           add_25[0][0]                     
____________________________________________________________________________________________________
block11_sepconv1 (SeparableConv2 (None, None, None, 72 536536      block11_sepconv1_act[0][0]       
____________________________________________________________________________________________________
block11_sepconv1_bn (BatchNormal (None, None, None, 72 2912        block11_sepconv1[0][0]           
____________________________________________________________________________________________________
block11_sepconv2_act (Activation (None, None, None, 72 0           block11_sepconv1_bn[0][0]        
____________________________________________________________________________________________________
block11_sepconv2 (SeparableConv2 (None, None, None, 72 536536      block11_sepconv2_act[0][0]       
____________________________________________________________________________________________________
block11_sepconv2_bn (BatchNormal (None, None, None, 72 2912        block11_sepconv2[0][0]           
____________________________________________________________________________________________________
block11_sepconv3_act (Activation (None, None, None, 72 0           block11_sepconv2_bn[0][0]        
____________________________________________________________________________________________________
block11_sepconv3 (SeparableConv2 (None, None, None, 72 536536      block11_sepconv3_act[0][0]       
____________________________________________________________________________________________________
block11_sepconv3_bn (BatchNormal (None, None, None, 72 2912        block11_sepconv3[0][0]           
____________________________________________________________________________________________________
add_26 (Add)                     (None, None, None, 72 0           block11_sepconv3_bn[0][0]        
                                                                   add_25[0][0]                     
____________________________________________________________________________________________________
block12_sepconv1_act (Activation (None, None, None, 72 0           add_26[0][0]                     
____________________________________________________________________________________________________
block12_sepconv1 (SeparableConv2 (None, None, None, 72 536536      block12_sepconv1_act[0][0]       
____________________________________________________________________________________________________
block12_sepconv1_bn (BatchNormal (None, None, None, 72 2912        block12_sepconv1[0][0]           
____________________________________________________________________________________________________
block12_sepconv2_act (Activation (None, None, None, 72 0           block12_sepconv1_bn[0][0]        
____________________________________________________________________________________________________
block12_sepconv2 (SeparableConv2 (None, None, None, 72 536536      block12_sepconv2_act[0][0]       
____________________________________________________________________________________________________
block12_sepconv2_bn (BatchNormal (None, None, None, 72 2912        block12_sepconv2[0][0]           
____________________________________________________________________________________________________
block12_sepconv3_act (Activation (None, None, None, 72 0           block12_sepconv2_bn[0][0]        
____________________________________________________________________________________________________
block12_sepconv3 (SeparableConv2 (None, None, None, 72 536536      block12_sepconv3_act[0][0]       
____________________________________________________________________________________________________
block12_sepconv3_bn (BatchNormal (None, None, None, 72 2912        block12_sepconv3[0][0]           
____________________________________________________________________________________________________
add_27 (Add)                     (None, None, None, 72 0           block12_sepconv3_bn[0][0]        
                                                                   add_26[0][0]                     
____________________________________________________________________________________________________
block13_sepconv1_act (Activation (None, None, None, 72 0           add_27[0][0]                     
____________________________________________________________________________________________________
block13_sepconv1 (SeparableConv2 (None, None, None, 72 536536      block13_sepconv1_act[0][0]       
____________________________________________________________________________________________________
block13_sepconv1_bn (BatchNormal (None, None, None, 72 2912        block13_sepconv1[0][0]           
____________________________________________________________________________________________________
block13_sepconv2_act (Activation (None, None, None, 72 0           block13_sepconv1_bn[0][0]        
____________________________________________________________________________________________________
block13_sepconv2 (SeparableConv2 (None, None, None, 10 752024      block13_sepconv2_act[0][0]       
____________________________________________________________________________________________________
block13_sepconv2_bn (BatchNormal (None, None, None, 10 4096        block13_sepconv2[0][0]           
____________________________________________________________________________________________________
conv2d_12 (Conv2D)               (None, None, None, 10 745472      add_27[0][0]                     
____________________________________________________________________________________________________
block13_pool (MaxPooling2D)      (None, None, None, 10 0           block13_sepconv2_bn[0][0]        
____________________________________________________________________________________________________
batch_normalization_16 (BatchNor (None, None, None, 10 4096        conv2d_12[0][0]                  
____________________________________________________________________________________________________
add_28 (Add)                     (None, None, None, 10 0           block13_pool[0][0]               
                                                                   batch_normalization_16[0][0]     
____________________________________________________________________________________________________
block14_sepconv1 (SeparableConv2 (None, None, None, 15 1582080     add_28[0][0]                     
____________________________________________________________________________________________________
block14_sepconv1_bn (BatchNormal (None, None, None, 15 6144        block14_sepconv1[0][0]           
____________________________________________________________________________________________________
block14_sepconv1_act (Activation (None, None, None, 15 0           block14_sepconv1_bn[0][0]        
____________________________________________________________________________________________________
block14_sepconv2 (SeparableConv2 (None, None, None, 20 3159552     block14_sepconv1_act[0][0]       
____________________________________________________________________________________________________
block14_sepconv2_bn (BatchNormal (None, None, None, 20 8192        block14_sepconv2[0][0]           
____________________________________________________________________________________________________
block14_sepconv2_act (Activation (None, None, None, 20 0           block14_sepconv2_bn[0][0]        
____________________________________________________________________________________________________
global_average_pooling2d_3 (Glob (None, 2048)          0           block14_sepconv2_act[0][0]       
____________________________________________________________________________________________________
dense_7 (Dense)                  (None, 2000)          4098000     global_average_pooling2d_3[0][0] 
____________________________________________________________________________________________________
batch_normalization_17 (BatchNor (None, 2000)          8000        dense_7[0][0]                    
____________________________________________________________________________________________________
activation_55 (Activation)       (None, 2000)          0           batch_normalization_17[0][0]     
____________________________________________________________________________________________________
dropout_4 (Dropout)              (None, 2000)          0           activation_55[0][0]              
____________________________________________________________________________________________________
dense_8 (Dense)                  (None, 133)           266133      dropout_4[0][0]                  
____________________________________________________________________________________________________
batch_normalization_18 (BatchNor (None, 133)           532         dense_8[0][0]                    
____________________________________________________________________________________________________
activation_56 (Activation)       (None, 133)           0           batch_normalization_18[0][0]     
====================================================================================================
Total params: 25,234,145
Trainable params: 24,794,407
Non-trainable params: 439,738
____________________________________________________________________________________________________
Epoch 1/20
Epoch 00000: val_acc improved from -inf to 0.78171, saving model to saved_models/weights.best.XceptionAugm.hdf5
266s - loss: 2.5494 - acc: 0.5518 - val_loss: 1.1301 - val_acc: 0.7817
Epoch 2/20
Epoch 00001: val_acc improved from 0.78171 to 0.81472, saving model to saved_models/weights.best.XceptionAugm.hdf5
258s - loss: 1.9190 - acc: 0.7464 - val_loss: 0.7626 - val_acc: 0.8147
Epoch 3/20
Epoch 00002: val_acc improved from 0.81472 to 0.82699, saving model to saved_models/weights.best.XceptionAugm.hdf5
256s - loss: 1.6960 - acc: 0.8169 - val_loss: 0.7229 - val_acc: 0.8270
Epoch 4/20
Epoch 00003: val_acc did not improve
255s - loss: 1.5423 - acc: 0.8708 - val_loss: 0.7676 - val_acc: 0.8135
Epoch 5/20
Epoch 00004: val_acc improved from 0.82699 to 0.84908, saving model to saved_models/weights.best.XceptionAugm.hdf5
257s - loss: 1.3912 - acc: 0.9085 - val_loss: 0.7533 - val_acc: 0.8491
Epoch 6/20
Epoch 00005: val_acc did not improve
256s - loss: 1.2899 - acc: 0.9298 - val_loss: 0.7610 - val_acc: 0.8356
Epoch 7/20
Epoch 00006: val_acc did not improve
256s - loss: 1.2056 - acc: 0.9464 - val_loss: 0.8115 - val_acc: 0.8442
Epoch 8/20
Epoch 00007: val_acc did not improve
255s - loss: 1.1412 - acc: 0.9537 - val_loss: 0.9223 - val_acc: 0.8160
Epoch 9/20
Epoch 00008: val_acc did not improve
255s - loss: 1.0718 - acc: 0.9563 - val_loss: 0.8555 - val_acc: 0.8454
Epoch 10/20
Epoch 00009: val_acc did not improve
256s - loss: 1.0329 - acc: 0.9614 - val_loss: 0.8192 - val_acc: 0.8429
Epoch 11/20
Epoch 00010: val_acc improved from 0.84908 to 0.85890, saving model to saved_models/weights.best.XceptionAugm.hdf5
256s - loss: 0.9670 - acc: 0.9726 - val_loss: 0.7696 - val_acc: 0.8589
Epoch 12/20
Epoch 00011: val_acc did not improve
255s - loss: 0.9319 - acc: 0.9757 - val_loss: 0.8071 - val_acc: 0.8552
Epoch 13/20
Epoch 00012: val_acc improved from 0.85890 to 0.86258, saving model to saved_models/weights.best.XceptionAugm.hdf5
257s - loss: 0.8922 - acc: 0.9802 - val_loss: 0.7594 - val_acc: 0.8626
Epoch 14/20
Epoch 00013: val_acc did not improve
256s - loss: 0.8450 - acc: 0.9826 - val_loss: 0.7526 - val_acc: 0.8589
Epoch 15/20
Epoch 00014: val_acc did not improve
256s - loss: 0.8035 - acc: 0.9843 - val_loss: 0.8162 - val_acc: 0.8598
Epoch 16/20
Epoch 00015: val_acc improved from 0.86258 to 0.87730, saving model to saved_models/weights.best.XceptionAugm.hdf5
256s - loss: 0.7592 - acc: 0.9906 - val_loss: 0.7396 - val_acc: 0.8773
Epoch 17/20
Epoch 00016: val_acc did not improve
256s - loss: 0.7420 - acc: 0.9903 - val_loss: 0.8299 - val_acc: 0.8540
Epoch 18/20
Epoch 00017: val_acc did not improve
255s - loss: 0.7096 - acc: 0.9903 - val_loss: 0.8548 - val_acc: 0.8626
Epoch 19/20
Epoch 00018: val_acc did not improve
256s - loss: 0.6781 - acc: 0.9904 - val_loss: 0.8074 - val_acc: 0.8503
Epoch 20/20
Epoch 00019: val_acc did not improve
255s - loss: 0.6421 - acc: 0.9912 - val_loss: 0.8936 - val_acc: 0.8356
Test accuracy: 86.7225%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [34]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import *
import cv2
import matplotlib.pyplot as plt                        
%matplotlib inline                               

def predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))

    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

# Test predict_breed on an image
dog_file = train_files[2]
print(dog_file)

# load color (BGR) image
img = cv2.imread(dog_file)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(cv_rgb)

dog_breed = predict_breed(dog_file)
print(dog_breed)
dogImages/train\088.Irish_water_spaniel\Irish_water_spaniel_06014.jpg
Irish_water_spaniel

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [35]:
# Create a dictionary of dogs by breed. It will be used later in
# prediction algorithm testing
dogs_by_breed = {name : [] for name in dog_names}

for i in range(len(train_targets)):
    dogs_by_breed[dog_names[np.argmax(train_targets[i])]].append(i)
In [36]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

import cv2
import matplotlib.pyplot as plt                        
%matplotlib inline               

NUM_EXAMPLES = 10

def detect_breed(img_path):
    img = cv2.imread(img_path)
    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)

    dog_breed = None
    if dog_detector(img_path):
        dog_breed = predict_breed(img_path)
        print('hello, dog!')
        print('Your predicted breed is ', dog_breed)
    elif face_detector(img_path):
        dog_breed = predict_breed(img_path)
        print('hello, human!')
        print('You look like a ', dog_breed)
    else:
        print('No human or dog detected!')
        
    # show examples of the breed
    if dog_breed:
        fig = plt.figure(figsize=(20,2))
        count = min(NUM_EXAMPLES, len(dogs_by_breed[dog_breed]))
        for i in range(count):
            ax = fig.add_subplot(1, count, i+1)
            ax.imshow(train_tensors[dogs_by_breed[dog_breed][i]])
        
        title = dog_breed + ' pictures'
        fig.suptitle(title, fontsize=20)
        plt.show()

        

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: The algorithm is pretty accurate in terms of detecting dog breeds. When I tested it on different variations of the Labrador breed, the algorithm correctly detected dogs breed. In regard to detecting dogs on images, I tested it on two cat pictures and for one of them the algorithm mistakenly found a dog there. I can't say if the dog breed prediction results are accurate for humans because it is very subjective. But I can see similarities between Donald Trump and Boston terriers.

Below are possible algorithm improvements:

  • we can use a better human and dog detection algorithm. For face recognition it could be something similar to the Facebook's DeepFace algorithm.
  • we can do a better pre-processing of the input images. For instance, when a human face is detected on the image, we can cut it and feed it to the network instead of the original image. By doing that we remove all the features from the image background that can potentially have an impact on the prediction.
  • in a similar manner, we can also localize and "cut" dogs on images using object localization techniques (ResNetCAM-keras).
In [37]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

detect_breed(train_files[1])
hello, dog!
Your predicted breed is  Dalmatian
In [38]:
detect_breed('images/donald-trump.jpg')
hello, human!
You look like a  Boston_terrier
In [39]:
detect_breed('images/tim_roth.jpg')
hello, human!
You look like a  Anatolian_shepherd_dog
In [40]:
detect_breed('images/Labrador_retriever_06457.jpg')
hello, dog!
Your predicted breed is  Labrador_retriever
In [41]:
detect_breed('images/Labrador_retriever_06455.jpg')
hello, dog!
Your predicted breed is  Labrador_retriever
In [42]:
detect_breed('images/Brittany_02625.jpg')
hello, dog!
Your predicted breed is  Brittany
In [43]:
detect_breed('images/cat1.jpg')
No human or dog detected!
In [44]:
detect_breed('images/cat2.jpg')
hello, human!
You look like a  Neapolitan_mastiff
In [45]:
detect_breed('images/sample_cnn.png')
No human or dog detected!